package org.net5ijy.security.validate;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.net5ijy.security.util.ApplicationSourceUtil;
import org.net5ijy.security.util.ValidateCodeUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * ImgValidateCodeGenerator
 *
 * @author XGF
 * @date 2020/11/30 22:21
 */
@Component("imgValidateCodeGenerator")
public class ImgValidateCodeGenerator implements ValidateCodeGenerator,
    InitializingBean {

  public static final String IMG_VALIDATE_CODE_SESSION_KEY = "imgValidateCode";

  /**
   * 有效期为60秒
   */
  private int expireIn = 60000;

  private int length = 4;

  @Override
  public ValidateCode generateValidateCode(HttpServletRequest request,
      HttpServletResponse response) throws IOException {
    // 生成随机字符串
    String codeStr = ValidateCodeUtil.createValidateCode(length);
    // 创建验证码对象
    ValidateCode code = new ValidateCode(codeStr, expireIn);
    // 把验证码放到session里面
    request.getSession().setAttribute(IMG_VALIDATE_CODE_SESSION_KEY, code);
    return code;
  }

  @Override
  public void sendValidateCode(ValidateCode code, HttpServletRequest request,
      HttpServletResponse response) throws IOException {
    // 生成图片
    BufferedImage image = ValidateCodeUtil.createImage(80, 30,
        code.getCode(), 15, false);
    // 输出到响应
    ValidateCodeUtil.out(image, response.getOutputStream());
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    ApplicationSourceUtil util = ApplicationSourceUtil
        .getApplicationSourceUtil();
    this.expireIn =
        util.getInteger("net5ijy.security.imgCode.expireIn", this.expireIn);
    this.length =
        util.getInteger("net5ijy.security.imgCode.length", this.length);
  }
}
